package com.jn.exam.webSocket.component;

import com.alibaba.fastjson.JSONObject;
import com.jn.exam.webSocket.config.ServerConfig;
import com.jn.exam.webSocket.entity.MessageResult;
import com.jn.exam.webSocket.utils.Constants;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 订阅消息
 *
 * @author 江南大学1033190417
 * @date 2022/3/4 20:35
 */
@Component
public class FanoutReceiver {

    @Value("#{queue.name}")
    private String name;


    @RabbitHandler
    @RabbitListener(queues = "#{queue.name}")//动态绑定
    public void receiveMessage(String jsonObject) {
        System.out.println("接收消息" + jsonObject);
        Map<String, MessageResult> map = JSONObject.parseObject(jsonObject, Map.class);
        if (!map.containsKey("0")) {
            Set<Map.Entry<String, MessageResult>> entries = map.entrySet();
            for (Map.Entry<String, MessageResult> entry : entries) {
                Map<String, Session> electricSocketMap = WebSocketServer.electricSocketMap;
                if (electricSocketMap.containsKey(entry.getKey())) {
                    Object obj = map.get(entry.getKey());
                    MessageResult result = (MessageResult) JSONObject.parseObject(obj.toString(), MessageResult.class);
                    WebSocketServer.sendMsg(electricSocketMap.get(entry.getKey()), result);
                }
            }
        } else if(map.containsKey("0")){//给所有监考老师发消息
            Object obj = map.get("0");
            MessageResult result = (MessageResult) JSONObject.parseObject(obj.toString(), MessageResult.class);
            String examId = result.getSingleId().split("-")[1];//拿到singleId里面的考试id
            ConcurrentHashMap<String, Session> electricSocketMap = WebSocketServer.electricSocketMap;
            Set<Map.Entry<String, Session>> entries = electricSocketMap.entrySet();
            for (Map.Entry<String, Session> entry : entries) {
                String singleId = entry.getKey();
                String[] split = singleId.split("-");
                if (examId.equals(split[1]) && "1".equals(split[2])) {//给目前在线的参考老师发消息，让他调用某些接口
                    WebSocketServer.sendMsg(electricSocketMap.get(entry.getKey()), result);
                }
            }
        }
    }
}
